package com.base.cn.platform.os.service.op.groom;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.op.groom.OpGroomDataDao;
import com.base.cn.platform.os.entity.manage.teacher.SysTeacher;
import com.base.cn.platform.os.entity.op.article.OpArticle;
import com.base.cn.platform.os.entity.op.groom.OpGroomData;
import com.base.cn.platform.os.entity.op.groom.OpGroomPlace;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.service.course.book.BookService;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.base.cn.platform.os.service.manage.teacher.SysTeacherBiz;
import com.base.cn.platform.os.service.op.article.OpArticleBiz;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 推荐数据表
 * Created by ll on 2018/05/07.
 */
@Service
public class OpGroomDataBiz extends BaseBiz<OpGroomData,OpGroomDataDao> {
    @Autowired
    private CourseService courseService;
    @Autowired
    private SysTeacherBiz sysTeacherBiz;
    @Autowired
    private OpGroomPlaceBiz opGroomPlaceBiz;
    @Autowired
    private BookService bookService;
    @Autowired
    private OpArticleBiz opArticleBiz;
    @Autowired
    private CusUserBiz cusUserBiz;
    /**
     * 搜索列表
     * @param groomData
     * @return
     */
    public List<OpGroomData> queryGroomDataList(OpGroomData groomData){
        String  whereSql = whereGroomData(groomData);
        return this.find(whereSql,groomData.getCount(),null);
    }

    /**
     * 搜索列表
     * @param groomData
     * @return
     */
    public PageInfo<OpGroomData> queryGroomDataListPage(OpGroomData groomData,Pagination page){
        String  whereSql = whereGroomData(groomData);
        return this.findPage(whereSql,page,null);
    }



    /**
     * 条件搜索语句
     * @param groomData
     * @return
     */
    public String whereGroomData(OpGroomData groomData){
        String whereSql = "1=1";
        if(ObjectUtils.isNotEmpty(groomData)){
            if(DataUtil.idIsNotNull(groomData.getDataId())){
                whereSql += " and dataId ="+groomData.getDataId();
            }
            if(StringUtils.isNotEmpty(groomData.getDataType())){
                whereSql+= " and dataType ='"+groomData.getDataType()+"'";
            }
            if(StringUtils.isNotEmpty(groomData.getPlaceKey())){
                whereSql += " and placeKey ='"+groomData.getPlaceKey()+"'";
            }
        }
        whereSql += " order by sort asc";
        return whereSql;
    }

    /**
     * 单个添加修改
     * @param dataType
     * @param placeKey
     * @return
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public void saveUpdateGroomData(OpGroomPlace opGroomPlace,List<OpGroomData> groomDatas,String dataType, String placeKey){
        if(ObjectUtils.isNotEmpty(opGroomPlace)){
            opGroomPlace.setDataType(dataType);
            opGroomPlaceBiz.updateById(opGroomPlace,null);
        }
        this.deleteWhereSql(" dataType ='"+dataType+"' and placeKey='"+placeKey+"'");
        if(ObjectUtils.isNotEmpty(groomDatas)){
            this.batchSave(groomDatas);
        }
    }


    /**
     * 批量添加推荐
     * @param opGroomDatas 推荐数据
     * @param dataType 推荐类型
     * @param placeIds 推荐位置Id
     * @return
     */
    @Transactional(rollbackFor =  IllegalArgumentException.class)
    public void savePlaceDataBatch(List<OpGroomData> opGroomDatas, String dataType,
                                                 String placeIds,String placeKey){
        this.deleteWhereSql(" dataType ='"+dataType+"' and placeKey in("+placeKey+")");
        this.batchSave(opGroomDatas);
        OpGroomPlace groomPlace = new OpGroomPlace();
        groomPlace.setDataType(dataType);
        opGroomPlaceBiz.updateByWhereSql(groomPlace," id in("+placeIds+")");
    }


    /**
     * 添加推荐数据
     * @param groomDatas
     */
    public void  setGroomDataByGroomPlace(List<OpGroomData> groomDatas){
        if(ObjectUtils.isNotEmpty(groomDatas)){
            String dataIds = groomDatas.stream().map(e->e.getDataId().toString()).collect(Collectors.joining(","));
            String dataType = groomDatas.get(0).getDataType();
            Map<BigDecimal,Map<String,Object>> groomTypeMap = new HashMap<>();
            if(dataType.equals("COURSE")||dataType.equals("PACKAGE") || dataType.equals("LIVE") || dataType.equals("SMALL")){
                HashMap<String, Object> parpm = new HashMap<>();
                parpm.put("ids",dataIds);
                List<Map<String, Object>> courseList = courseService.findCourseList(parpm, true, false, false, true);
                groomTypeMap =  courseList.stream().collect(Collectors.toMap(e -> new BigDecimal(e.get("id").toString()), e -> e));
            }
            if(dataType.equals("TEACHER")){
                Map<BigDecimal,SysTeacher>  _groomTypeMap= sysTeacherBiz.findSysTeacherToMapByIds(dataIds,false,false,false, false, false);
                if(ObjectUtils.isNotEmpty(_groomTypeMap)){
                    List<BigDecimal> keyList = new ArrayList<>(_groomTypeMap.keySet());
                    for(BigDecimal key : keyList ){
                        SysTeacher teacher = _groomTypeMap.get(key);
                        Map<String,Object> teacherMap = new HashMap<>();
                        teacherMap.put("id",teacher.getId());
                        teacherMap.put("teacherName",teacher.getTeacherName());
                        teacherMap.put("subjectIds",teacher.getSubjectIds());
                        teacherMap.put("sysUserId",teacher.getSysUserId());
                        teacherMap.put("imageJson",teacher.getImageJson());
                        teacherMap.put("imageMap",teacher.getImageMap());
                        teacherMap.put("teacherType",teacher.getTeacherType());
                        teacherMap.put("isQuestion",teacher.getIsQuestion());
                        teacherMap.put("qaTypeId",teacher.getQaTypeId());
                        teacherMap.put("questionFee",teacher.getQuestionFee());
                        teacherMap.put("courseNum",teacher.getCourseNum());
                        teacherMap.put("questionNum",teacher.getQuestionNum());
                        teacherMap.put("userNum",teacher.getUserNum());
                        teacherMap.put("depict",teacher.getDepict());
                        groomTypeMap.put(key,teacherMap);
                    }
                }
            }
            if(dataType.equals("ARTICLE")){
                Map<BigDecimal,OpArticle> _groomTypeMap = opArticleBiz.opArticleMapByIds(dataIds,0,true,true);
                if(ObjectUtils.isNotEmpty(_groomTypeMap)){
                    List<BigDecimal> keyList = new ArrayList<>(_groomTypeMap.keySet());
                    for(BigDecimal key : keyList ){
                        OpArticle article = _groomTypeMap.get(key);
                        Map<String,Object> articleMap = new HashMap<>();
                        articleMap.put("id",article.getId());
                        articleMap.put("typeId",article.getTypeId());
                        articleMap.put("imageMap",article.getImageMap());
                        articleMap.put("imageJson",article.getImageJson());
                        articleMap.put("title",article.getTitle());
                        articleMap.put("author",article.getAuthor());
                        articleMap.put("briefIntroduction",article.getBriefIntroduction());
                        articleMap.put("keyWord",article.getKeyWord());
                        articleMap.put("link",article.getLink());
                        articleMap.put("clickNum",article.getClickNum());
                        articleMap.put("releaseStatus",article.getReleaseStatus());
                        articleMap.put("createTime",article.getCreateTime());
                        articleMap.put("updateTime",article.getUpdateTime());
                        groomTypeMap.put(key,articleMap);
                    }
                }
            }
            if(dataType.equals("BOOK")){
                groomTypeMap=bookService.findBookMapByIds(dataIds,false,false);
            }
            if (dataType.equals("USER")){
                Map<BigDecimal,CusUser> _groomTypeMap = cusUserBiz.queryCusUserMapByUserIds(dataIds,false,false,false,false,false,false,false);
                if(ObjectUtils.isNotEmpty(_groomTypeMap)){
                    List<BigDecimal> keyList = new ArrayList<>(_groomTypeMap.keySet());
                    for(BigDecimal key : keyList ){
                        CusUser user = _groomTypeMap.get(key);
                        Map<String,Object> userMap = new HashMap<>();
                        userMap.put("id",user.getId());
                        userMap.put("nickname",user.getNickname());
                        userMap.put("realName",user.getRealName());
                        userMap.put("avatar",user.getAvatar());
                        groomTypeMap.put(key,userMap);
                    }
                }
            }
            if(ObjectUtils.isNotEmpty(groomTypeMap)){
                for (OpGroomData _groomData: groomDatas){
                    if(groomTypeMap.get(_groomData.getDataId())!=null){
                        _groomData.setDataTypeMap(groomTypeMap.get(_groomData.getDataId()));
                    }
                }
            }
        }
    }

    /**+
     * 清空推荐位置
     * @param dataType
     * @param placeKey
     */
    public void deleteGroomData(String dataType, String placeKey) {
        this.deleteWhereSql(" dataType ='" + dataType + "' and placeKey='" + placeKey + "'");
    }

    /**
     * 删除推荐数据，通过数据ID串和数据类型
     * @param dataIds 数据ID
     * @param dataType 数据类型
     */
    public void deleteGroomDataByDataIdAndDataType(String dataIds,String dataType){
        StringBuilder _dataType = new StringBuilder();
        _dataType.append("'").append(dataType).append("'");
        if(dataType.equals("COURSE")){
            _dataType.append(",'PACKAGE'");
        }
        this.deleteWhereSql(" dataType in ("+_dataType+") and dataId in ("+dataIds+")");
    }


}
